package ui.login


import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.window.WindowDraggableArea
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.onPointerEvent
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowPosition
import androidx.compose.ui.window.rememberWindowState
import state.ApplicationWindowsState
import state.WindowType
import theme.EasyChatTheme
import ui.compose.NetworkImage
import ui.compose.RectIconButton
import java.net.URL


/**
 * @author wei kunJie
 * @date 2024/3/7 20:13:54
 */
@OptIn(ExperimentalMaterialApi::class, ExperimentalComposeUiApi::class)
@Composable
fun loginWindows(
    easyChatTheme: MutableState<EasyChatTheme>,
    applicationWindowsState: ApplicationWindowsState,
    close: () -> Unit
) = Window(
    icon = painterResource("icon/ic_logo.svg"),
    transparent = true,//设置为透明窗口
    undecorated = true, //透明窗口必须取消装饰，这样就没默认的窗口标题栏和那些最小化、最大化、关闭什么的了
    onCloseRequest = close,
    title = "登陆",
    state = rememberWindowState(width = 330.dp, height = 462.dp, position = WindowPosition(Alignment.Center))
) {
    //rememberCoroutineScope() 是一个用于在 Composable 函数中创建协程作用域
    val coroutineScope = rememberCoroutineScope()
    //创建ViewModel
    val viewModel = remember { LoginViewModel(applicationWindowsState, coroutineScope) }
    val windowsCorner = 5.dp//窗口圆角大小
    //窗口表面，用来定窗口样式
    Surface(
        modifier = Modifier.fillMaxSize().padding(5.dp)
            .shadow(3.dp, RoundedCornerShape(windowsCorner + 3.dp)),//窗口阴影样式
        color = Color(0xFFE2F5FF),
        shape = RoundedCornerShape(windowsCorner) //窗口圆角
    ) {
        Row(
            modifier = Modifier.padding(top = 60.dp).fillMaxWidth()
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier.fillMaxWidth()
            ) {
                //加载网络图片
                NetworkImage(
                    url = viewModel.avatar.value,
                    painterFor = { remember { BitmapPainter(it) } },
                    contentDescription = "头像",
                    modifier = Modifier.size(100.dp).clip(CircleShape),
                    contentScale = ContentScale.Crop,
                    defaultPainterFor = painterResource("image/default_head.png")
                )
                val expanded = remember { mutableStateOf(false) }
                //账号输入
                ExposedDropdownMenuBox(
                    modifier = Modifier.padding(top = 20.dp),
                    expanded = expanded.value,
                    onExpandedChange = {
                        expanded.value = !expanded.value
                    },
                ) {
                    TextField(
                        modifier = Modifier.height(50.dp).width(280.dp),
                        value = viewModel.userAccount.value,
                        onValueChange = { viewModel.userAccount.value = it },
                        shape = RoundedCornerShape(7.dp),
                        colors = TextFieldDefaults.outlinedTextFieldColors(
                            backgroundColor = Color(0xFFFFFFFF),
                            focusedBorderColor = Color.Transparent,
                            unfocusedBorderColor = Color.Transparent,
                            cursorColor = Color.Black
                        ),
                        singleLine = true,
                        textStyle = TextStyle(
                            fontSize = 15.sp // 设置字体大小
                        ),
                        placeholder = {
                            Text(
                                text = "请输入E-Chat账号",
                                style = TextStyle(
                                    textAlign = TextAlign.Center,
                                    fontSize = 15.sp,
                                    color = Color.Gray
                                ),
                            )
                        },
                        trailingIcon = {
                            ExposedDropdownMenuDefaults.TrailingIcon(
                                expanded = expanded.value,
                                onIconClick = {
                                    expanded.value = true
                                }
                            )
                        }
                    )
                    ExposedDropdownMenu(expanded = expanded.value,
                        onDismissRequest = {
                            expanded.value = false
                        }) {
                        viewModel.allUserList.forEach {
                            if (viewModel.userAccount.value != it.account) {
                                DropdownMenuItem(onClick = {
                                    viewModel.avatar.value = it.avatar.toString()
                                    viewModel.userAccount.value = it.account.toString()
                                    viewModel.userPassword.value = it.password.toString()
                                    expanded.value = false
                                }) {
                                    Row(verticalAlignment = Alignment.CenterVertically) {
                                        NetworkImage(
                                            url = it.avatar.toString(),
                                            painterFor = { remember { BitmapPainter(it) } },
                                            contentDescription = "头像",
                                            modifier = Modifier.size(30.dp).clip(CircleShape),
                                            contentScale = ContentScale.Crop,
                                            defaultPainterFor = painterResource("image/default_head.png")
                                        )
                                        Spacer(modifier = Modifier.width(10.dp))
                                        Text(text = it.account.toString())
                                    }
                                }
                            }
                        }

                    }
                }

                //密码输入
                TextField(
                    value = viewModel.userPassword.value,
                    onValueChange = { viewModel.userPassword.value = it },
                    shape = RoundedCornerShape(7.dp),
                    modifier = Modifier.padding(top = 16.dp).height(50.dp).width(280.dp),
                    visualTransformation = PasswordVisualTransformation('*'),
                    colors = TextFieldDefaults.outlinedTextFieldColors(
                        backgroundColor = Color(0xFFFFFFFF),
                        focusedBorderColor = Color.Transparent,
                        unfocusedBorderColor = Color.Transparent,
                    ),
                    singleLine = true,
                    textStyle = TextStyle(
                        fontSize = 15.sp // 设置字体大小
                    ),
                    placeholder = {
                        Text(
                            text = "请输入E-Chat密码",
                            style = TextStyle(
                                textAlign = TextAlign.Center,
                                fontSize = 15.sp,
                                color = Color.Gray
                            ),
                        )
                    }
                )
                //登陆按钮

                Button(
                    modifier = Modifier.padding(top = 25.dp).height(40.dp).width(280.dp),
                    onClick = {
                        viewModel.loginBtnEnable.value = false
                        viewModel.login(easyChatTheme)
                    },
                    shape = RoundedCornerShape(7.dp),
                    colors = ButtonDefaults.buttonColors(
                        backgroundColor = Color(0xFF0099FF),
                    ),
                    enabled = viewModel.loginBtnEnable.value
                ) {
                    Text(
                        text = "登录",
                        style = TextStyle(
                            textAlign = TextAlign.Center,
                            fontSize = 15.sp,
                            color = Color.White
                        )
                    )
                }

                Row(modifier = Modifier.padding(top = 25.dp)) {
                    TextButton(onClick = {

                    }) {
                        Text(
                            text = "扫码登陆",
                            style = TextStyle(
                                textAlign = TextAlign.Center,
                                fontSize = 13.sp,
                                color = Color(0xFF0099FF)
                            )
                        )
                    }
                    TextButton(
                        modifier = Modifier.padding(horizontal = 5.dp),
                        onClick = {

                        }) {
                        Text(
                            text = "注册账号",
                            style = TextStyle(
                                textAlign = TextAlign.Center,
                                fontSize = 13.sp,
                                color = Color(0xFF0099FF)
                            )
                        )
                    }
                    TextButton(onClick = {

                    }) {
                        Text(
                            text = "忘记密码",
                            style = TextStyle(
                                textAlign = TextAlign.Center,
                                fontSize = 13.sp,
                                color = Color(0xFF0099FF)
                            )
                        )
                    }

                }
            }

        }
    }
    //窗口可拖动区域，鼠标按住后可以拖动窗口
    WindowDraggableArea {
        Surface(
            modifier = Modifier.fillMaxWidth().height(Dp(45f)).padding(5.dp),
            color = Color(0xFFE2F5FF),
//            color = Color(0xFFC75450),
            shape = RoundedCornerShape(windowsCorner, windowsCorner)
        ) {
            val isMouseIn = remember { mutableStateOf(false) }
            Box(contentAlignment = Alignment.TopEnd, modifier = Modifier
                ) {
                RectIconButton(
                    onClick = close,
                    modifier = Modifier.size(33.dp).background(
                        color = if (isMouseIn.value) Color(0xFFC42B1C)
                        else Color.Transparent
                    ).onPointerEvent(PointerEventType.Enter) { isMouseIn.value = true }
                        .onPointerEvent(PointerEventType.Exit) { isMouseIn.value = false },
                ) {
                    Icon(
                        painter = painterResource("icon/ic_close.svg"),
                        contentDescription = "关闭",
                        tint = if (isMouseIn.value) Color.White else Color.Black,
                        modifier = Modifier.size(33.dp).padding(9.dp)
                    )
                }
            }
        }
    }
    if (viewModel.loginStateDialogShow.value) {
        //登陆状态的提示对话框，如登陆失败提示
        AlertDialog(
            onDismissRequest = {
                viewModel.loginStateDialogShow.value = false
            },
            title = {
                Text(
                    text = viewModel.loginStateDialogMsg.value,
                    fontWeight = FontWeight.W400,
                    style = TextStyle(
                        textAlign = TextAlign.Center,
                        fontSize = 16.sp,
                        color = Color.Black
                    )
                )
            },
            buttons = {
                Row(
                    modifier = Modifier.padding(all = 10.dp).width(200.dp),
                    horizontalArrangement = Arrangement.Center
                ) {
                    Button(
                        modifier = Modifier.fillMaxWidth(),
                        onClick = { viewModel.loginStateDialogShow.value = false },
                        colors = ButtonDefaults.buttonColors(
                            backgroundColor = Color(0xFF0099FF),
                        )
                    ) {
                        Text(text = "我知道了", color = Color.White)
                    }
                }
            }
        )
    }
}
